import datetime
import pylab as plt
import math
import os
import random

from params import *
from plotter import *
from fit import *
from qqplot import *

STEP = 1
STEP_NAME = 'days'
STEP = 7
STEP_NAME = 'weeks'
STEP = 30
STEP_NAME = 'months'
THRESHOLD = 0
MAX = 360/STEP
LIMIT = math.ceil(MAX)
XLBL = 'Activity span in %s'%STEP_NAME

def get_activity(d1,d2):
    format = "%Y-%m-%d"
    d1 = datetime.date(*map(int,d1.split('-')))
    d2 = datetime.date(*map(int,d2.split('-')))
    delta = (d2-d1).days
    delta /= STEP
    return delta
    
def get_age(d1,d2):
    format = "%Y-%m-%d"
    d1 = datetime.date(*map(int,d1.split('-')))
    d2 = datetime.date(2010,8,18)
    delta = (d2-d1).days
    delta /= STEP
    return delta

graph_file = os.path.join(WORKDIR, 'gowalla', 'stats',
    'gowalla_network_snapshot_2010-08-18.txt')
activity_file = os.path.join(WORKDIR, 'gowalla', 'stats',
    'gowalla_user_activity.txt')

user_degree = {}
for line in open(graph_file):
    if line.startswith('#'):
        continue
    n1,n2 = map(int,line.split()[:2])
    user_degree.setdefault(n1,0)
    user_degree.setdefault(n2,0)
    user_degree[n1] += 1
    user_degree[n2] += 1

user_age = {}
user_activity = {}
user_places = {}
user_checkins = {}
for line in open(activity_file):
    user, d1, d2, num_places,num_checkins = line.strip().split()
    user = int(user)
    user_age[user] = get_age(d1,d2)
    user_activity[user] = get_activity(d1,d2)
    user_places[user] = int(num_places)
    user_checkins[user] = int(num_checkins)


def plot(user_values, title,exp=False):
    months = [2,5,10,12]
    months = range(1,20)
    M = max(months)
    data = []
    for m in months:
        values = []
        for u in user_activity:
            k = min((M,user_activity[u]))
            if m == k:
                if u in user_values:
                    values.append(user_values[u])
        #values = filter(lambda i: i > 1, values)
        N = 1000
        if len(values) > N:
            values = random.sample(values,N)
        p = Plotter(values)
        x = p.x
        c = p.c
        qq = QQPlot(values)
        xf,cf = qq.t_plot()
        #l = LogNormalFit(values)
        #l.fit()
        #xf,yf = l.fitted_ccdf()
        data.append((x,c,xf,cf,m))

    QQ = True
    PP = False
    if QQ:
        plt.figure()
        plt.clf()
        plt.axes(FIG_AXES2)
        i = 0
        leg = []
        for x,c,xf,cf,m in data:
            print len(xf)
            plt.plot(xf,cf,'c,', mfc='None', mec='c')
        V = 3
        plt.plot([-V,V],[-V,V], 'k-')
        plt.axis([-V,V,-V,V])
        plt.xlabel('Theoretical quantiles')
        plt.ylabel('Data quantiles')
        plt.grid(True)
        plt.savefig('gowalla_conditioned_qqplot_%s.pdf'%title)
        plt.close()

#    if PP:
#        plt.figure()
#        plt.clf()
#        plt.axes(FIG_AXES2)
#        i = 0
#        leg = []
#        for x,c,xf,yf,m in data:
#            mark = 'c%s'%symbols[i]
#            mark2 = 'k%s'%symbols[i]
#            i += 1
#            if exp:
#                print 'exp'
#                plt.semilogy(x,c,mark)
#            else:
#                print 'loglog'
#                plt.loglog(x,c,mark)
#                #plt.loglog(xf,yf,mark2)
#            leg.append('Month %d'%m)
#        plt.grid(True)
#        plt.legend(leg,numpoints=1,loc='lower left')
#        plt.savefig('gowalla_conditioned_%s.pdf'%title)
#        plt.close()

plot(user_degree,'degree')
plot(user_checkins,'checkin')
plot(user_places,'place')#,exp=True)
